package com.eastsunsoft.swordfish.ucms.base.impl;

import com.eastsunsoft.swordfish.common.ApiConstant;
import com.eastsunsoft.swordfish.common.SwordfishException;
import com.eastsunsoft.swordfish.ucms.base.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

/**
 * BaseServiceImpl
 *
 * @author donny
 * @date 03/12/2016
 */
@Service
@Transactional
public abstract class BaseServiceImpl<T> implements BaseService<T> {
    protected Mapper<T> mapper;

    public BaseServiceImpl(Mapper<T> mapper) {
        this.mapper = mapper;
    }

    @Override
    @Transactional(readOnly = true)
    public T get(Object id) {
        T t = mapper.selectByPrimaryKey(id);
        if (t == null) {
            throw new SwordfishException(ApiConstant.ERRCODE_RECORD_NOT_EXISTS);
        }

        return t;
    }

    @Override
    public <S extends T> S save(S entity) {
        mapper.insertSelective(entity);
        return entity;
    }
}
